package data

import (
	"entgo.io/ent/dialect/sql"
	"github.com/google/wire"
	"helloworld/internal/conf"
	"helloworld/internal/data/ent"

	"github.com/go-kratos/kratos/v2/log"
	_ "github.com/lib/pq" // PostgreSQL driver
)

// ProviderSet is data providers.
var ProviderSet = wire.NewSet(NewData, NewUserRepo)

// Data .
type Data struct {
	db *ent.Client
}

// NewData .
func NewData(conf *conf.Data, logger log.Logger) (*Data, func(), error) {
	log := log.NewHelper(logger)
	drv, err := sql.Open(
		conf.Database.Driver,
		conf.Database.Source,
	)
	if err != nil {
		log.Errorf("failed opening connection to postgresql: %v", err)
		return nil, nil, err
	}

	// 创建 ent.Client 并设置驱动
	client := ent.NewClient(ent.Driver(drv))

	// 初始化 Data 结构体
	d := &Data{
		db: client,
	}

	// 返回关闭函数，用于在程序结束时关闭数据库连接
	cleanup := func() {
		log.Info("closing the data resources")
		if err := d.db.Close(); err != nil {
			log.Error(err)
		}
	}

	return d, cleanup, nil
}
